package com.sample.library.util;


import com.sample.library.BaseViewModel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ClassUtil {

    /**
     * 获取泛型ViewModel的class对象
     */
    public static <T> Class<T> getViewModel(Object obj) {
        Class<?> currentClass = obj.getClass();
        return getGenericClass(currentClass);
    }

    private static <T> Class<T> getGenericClass(Class<?> klass) {
        Type type = klass.getGenericSuperclass();

        if (!(type instanceof ParameterizedType)) {
            return null;
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type[] types = parameterizedType.getActualTypeArguments();

        for (Type t : types) {
            if (t.getClass().getSimpleName().equals("Class")) {
                Class<T> tClass = (Class<T>) t;

                if (BaseViewModel.class.isAssignableFrom(tClass)) {
                    return tClass;
                }
            } else {
                //如果ViewModel里面有泛型 会执行下面的逻辑
                ParameterizedType parameter = (ParameterizedType) t;
                return (Class<T>) parameter.getRawType();
            }
        }
        return null;
    }
}
